package com.wu.leetcode.leetcode219;

import java.util.HashMap;
import java.util.HashSet;

/**
 * Leetcode219-存在重复元素 II
 *
 * @author lynn
 * @date 2020/10/28 - 17:48
 */
public class Solution {
    public static boolean containsNearbyDuplicate(int[] nums, int k) {

        //nums = [1,0,1,1], k = 1
        if (nums == null || nums.length == 0) {
            return false;
        }
       /* HashMap<Integer, Integer> map = new HashMap<>();
        int res = Integer.MAX_VALUE;
        Boolean flag = false;
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                flag = true;
                res = res <  i - map.get(nums[i]) ? res : i - map.get(nums[i]);
            }
            map.put(nums[i], i);
        }
        return res <= k && flag == true;*/
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                return true;
            }
            set.add(nums[i]);
            if (set.size() > k) {
                set.remove(nums[i - k]);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 2};
        boolean b = containsNearbyDuplicate(nums, 3);
        System.out.println(b);
    }
}
